from django import forms

from models import Object, Attribute, AttributeImplication, ObjectImplication

class ObjectForm(forms.ModelForm):
    class Meta:
        model = Object
        fields = ('name', 'attributes', 'type', 'description')
      
class AttributeForm(forms.ModelForm):
    class Meta:
        model = Attribute
        
    object_set = forms.ModelMultipleChoiceField(queryset=Object.objects.all(),
                                                required=False)

    def __init__(self, *args, **kwargs):
        if 'instance' in kwargs:           
            initial = kwargs.setdefault('initial', {})
            initial['object_set'] = [t.pk for t in kwargs['instance'].object_set.all()]

        forms.ModelForm.__init__(self, *args, **kwargs)

    def save(self, commit=True):
        instance = forms.ModelForm.save(self, False)

        old_save_m2m = self.save_m2m
        def save_m2m():
            old_save_m2m()
            instance.object_set.clear()
            for object_ in self.cleaned_data['object_set']:
                instance.object_set.add(object_)
        self.save_m2m = save_m2m

        if commit:
            instance.save()
            self.save_m2m()

        return instance
    
class AttributeImplicationForm(forms.ModelForm):
    class Meta:
        model = AttributeImplication
        #fields = ('premise', 'conclusion')
        #widgets = {
            #'premise': forms.Textarea(attrs={'cols': 10, 'rows': 1}),
            #'conclusion': forms.Textarea(attrs={'cols': 10, 'rows': 1})
        #}

        
class ObjectImplicationForm(forms.ModelForm):
    class Meta:
        model = ObjectImplication
        #fields = ('premise', 'conclusion')